package com.baichen.spring.web;

import com.alibaba.fastjson2.JSON;
import com.baichen.spring.BeanPostProcesser;
import com.baichen.spring.Component;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class DispatcherServlet extends HttpServlet implements BeanPostProcesser {

    private static final Pattern PATTERN = Pattern.compile("baichen\\{(.*?)}");

    private HashMap<String, WebHandler> handlerMapping = new HashMap<>();
    private List<HandlerInterceptor> interceptors = new ArrayList<>();

    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        WebHandler webHandler = findHandler(req);
        if (webHandler == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found");
            return;
        }
        Exception ex = null;
        Object result = null;
        try {
            // 1. preHandle
            for (HandlerInterceptor interceptor : interceptors) {
                if (!interceptor.preHandle(req, resp, webHandler)) {
                    return;
                }
            }
            Object controllerBean = webHandler.getControllerBean();
            Object[] args = resolveArgs(req, webHandler.getMethod());
            result = webHandler.getMethod().invoke(controllerBean, args);
            // 2. postHandle
            for (HandlerInterceptor interceptor : interceptors) {
                interceptor.postHandle(req, resp, webHandler, result);
            }
            switch (webHandler.getResultType()) {
                case JSON:
                    resp.setContentType("application/json;charset=UTF-8");
                    resp.getWriter().write(JSON.toJSONString(result));
                    break;
                case HTML:
                    resp.setContentType("text/html;charset=UTF-8");
                    resp.getWriter().write(result.toString());
                    break;
                case LOCAL:
                    resp.setContentType("text/html;charset=UTF-8");
                    ModelAndView modelAndView = (ModelAndView) result;
                    String html =
                            new String(this.getClass().getClassLoader().getResourceAsStream(modelAndView.getView()).readAllBytes());
                    html = renderTemplate(html, modelAndView.getContext());
                    resp.getWriter().write(html);
                    break;
            }
        } catch (Exception e) {
            ex = e;
            throw new RuntimeException(e);
        } finally {
            // 3. afterCompletion
            for (HandlerInterceptor interceptor : interceptors) {
                try {
                    interceptor.afterCompletion(req, resp, webHandler, ex);
                } catch (Exception ignore) {}
            }
        }
    }

    private WebHandler findHandler(HttpServletRequest req) {
        return handlerMapping.get(req.getRequestURI());
    }

    private Object[] resolveArgs(HttpServletRequest req, Method method) {
        Parameter[] parameters = method.getParameters();
        Object[] args = new Object[parameters.length];

        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            String value = null;
            if (parameter.isAnnotationPresent(Param.class)) {
                value = req.getParameter(parameter.getAnnotation(Param.class).value());
            } else {
                value = req.getParameter(parameter.getName());
            }

            Class<?> type = parameter.getType();
            if (String.class.isAssignableFrom(type)) {
                args[i] = value;
            } else if (Integer.class.isAssignableFrom(type)) {
                args[i] = Integer.parseInt(value);
            } else {
                args[i] = null;
            }
        }

        return args;
    }
    private String renderTemplate(String template, Map<String, String> context) {
        Matcher matcher = PATTERN.matcher(template);
        StringBuilder sb = new StringBuilder();
        while (matcher.find()) {
            String key = matcher.group(1);
            String value = context.getOrDefault(key, "");
            matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }


    @Override
    public Object afterInitializeBean(Object bean, String beanName) {
        // 自动收集拦截器
        if (bean instanceof HandlerInterceptor) {
            interceptors.add((HandlerInterceptor) bean);
        }
        if (!bean.getClass().isAnnotationPresent(Controller.class)) {
           return bean;
        }

        String baseUrl = bean.getClass().isAnnotationPresent(RequestMapping.class) ?
                bean.getClass().getAnnotation(RequestMapping.class).value() : "";

        Arrays.stream(bean.getClass().getDeclaredMethods()).forEach(m -> {
            if (m.isAnnotationPresent(RequestMapping.class)) {
                String url = baseUrl + m.getAnnotation(RequestMapping.class).value();
                if (handlerMapping.put(url, new WebHandler(bean, m)) != null) {
                    throw new RuntimeException("Duplicate URL mapping: " + url);
                }
            }
        });

        return bean;
    }
}
